<?php

function migrateUsers()
{
    $db = db::$db;

    // Temporarily disable foreign key checks
    $db->exec("SET FOREIGN_KEY_CHECKS=0");

    // Drop the existing users table if it exists
    $sql = "DROP TABLE IF EXISTS users";
    $db->exec($sql);

    // Create the users table with proper column definitions
    $sql = "CREATE TABLE IF NOT EXISTS users (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        email VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(250) NOT NULL,
        user_name TEXT,
        avatar TEXT,
        wishlist TEXT,
        myroutes TEXT,
        first_name VARCHAR(80),
        second_name VARCHAR(80),
        invalidnost VARCHAR(80),
        comment TEXT
    )";

    $db->exec($sql);

    // Re-enable foreign key checks
    $db->exec("SET FOREIGN_KEY_CHECKS=1");
}

function _userRegister() {
    $email = Req::$data['email'];
    $password = Req::$data['password'];
   // $userName = Req::$data['user_name'];
    $db=db::$db;
    $stmt = $db->prepare("INSERT INTO users (email, password ) VALUES (?, ?)");
    $stmt->execute([$email, $password]);
    $id = $db->lastInsertId();
    if ($id) {
        $token = hash_hmac('sha256', $id, SECRET_KEY).'_'.$id;
        $user = $db->query("SELECT * FROM users WHERE id = $id")->fetch(PDO::FETCH_ASSOC);
        return ['user'=>$user, 'token'=>$token];
    }
    return null;
}

function _login() {
    $email = Req::$data['email'];
    $password = Req::$data['password'];
    $db=db::$db;
    $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
        $token = hash_hmac('sha256', $user['id'], SECRET_KEY).'_'.$user['id'];
        unset($user['password']);
        return ['user'=>$user, 'token'=>$token];
    } else {
        return null;
    }
}

function _logout() {
    logout();
    echo json_encode(['success' => true]);
}

function saveUserInfo()
{
    $db = db::$db;
    $userId = (int) verifyToken(Req::$data['token'] ?? 0);

    $fields = [];
    $values = [];

    $allowedFields = [
        'email', 'password', 'user_name', 'avatar',
        'wishlist', 'myroutes', 'first_name', 'second_name', 'invalidnost'
    ];

    foreach ($allowedFields as $field) {
        if (isset(Req::$data[$field])) {
            if ($field === 'password') {
                $fields[] = "$field = ?";
                $values[] = password_hash(Req::$data[$field], PASSWORD_BCRYPT);
            } else {
                $fields[] = "$field = ?";
                $values[] = Req::$data[$field];
            }

        }
    }

    if (empty($fields)) {
        echo json_encode(['success' => false, 'error' => 'No data provided to update']);
        return;
    }

    $values[] = $userId;
    $sql = "UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?";
    $stmt = $db->prepare($sql);

    try {
        $stmt->execute($values);
        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
}

function verifyToken($token)
{

    $parts = explode('_', $token);
    if (count($parts) !== 2) {
        exit;
    }

    $hash = $parts[0];
    $user_id = $parts[1];

    $expectedHash = hash_hmac('sha256', $user_id, SECRET_KEY);

    if (hash_equals($expectedHash, $hash)) {
        return $user_id;
    }
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

function createToken()
{

}